import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @作者 ： pwx5328113 @时间： 2023/3/6 @测试点 autoBalance配置为false或者不配置该参数，不进行负载均衡
 **/
public class JDBC_QuikAutoBalance_Case0003 {
	public static void main(String[] args) throws Exception {
		System.out.println("--------start--------");
		List<Connection> connections = new ArrayList<>();
		System.out.println("--------进行10个建连--------");
		// autoBalance为false
		String url1 = "jdbc:postgresql://" + args[0] + "/" + args[1] + "?loggerLevel=info&autoBalance=false";
		for (int i = 0; i < 10; i++) {
			try {
				Connection connection = DriverManager.getConnection(url1, args[2], args[3]);
				connections.add(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("--------sleep 10s--------");
		// sleep过程中，数据库实际节点查询上个操作每个节点实际连接数
		TimeUnit.SECONDS.sleep(10);
		System.out.println("--------connections close start--------");
		for (Connection connection : connections) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("--------connections close end--------");

		System.out.println("--------再次进行5个建连--------");
		// autoBalance不配置该参数
		String url2 = "jdbc:postgresql://" + args[0] + "/" + args[1] + "?loggerLevel=info";
		for (int i = 0; i < 5; i++) {
			try {
				Connection connection = DriverManager.getConnection(url2, args[2], args[3]);
				connections.add(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("--------sleep 10s--------");
		TimeUnit.SECONDS.sleep(10);
		// sleep过程中，数据库实际节点查询上个操作每个节点实际连接数
		System.out.println("--------connections close start--------");
		for (Connection connection : connections) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("--------connections close end--------");
	}
}
